let path = require('path');
let fs = require('fs');
let express = require('express');
let router = express.Router();
let Tools = require('../tools');

let { projectModel, userModel } = require('../service');

/**
 * 登陆界面
 */
router.get('/login', (req, res, next) => {
  res.render('login.html', {
    title: `登陆-DOC文章管理`
  });
});

/**
 * 登陆接口
 */
router.post('/log-in', (req, res, next) => {
  let resultUser = userModel.find({
    u: req.body.u,
    p: req.body.p
  });
  if(!!resultUser){
    req.session.userinfo = resultUser;
    req.session.messages = {
      type: 'success',
      msg: "登陆成功"
    };
    res.redirect('/');
  } else {
    req.session.messages = {
      type: 'error',
      msg: "用户名或密码错误"
    };
    res.redirect('/login');
  }
});

/**
 * 主页
 */
router.get('/', (req, res, next) => {
  let prjList = projectModel.findAll({
    status: 1
  });
  prjList = prjList.map(item => {
    return Object.assign({}, item, {
      editorURL: 'edit/' + item.uuid,
      viewURL: global.editorPreviewPath.substr(1) + '/' + item.uuid,
      qrcodeUrl: Tools.getQrcodeImageUrl(`${req.protocol}://${req.get('host')}/view/${item.uuid}`, {
        size: '100x100',
        margin: '5'
      })
    });
  });
  res.render('index.html', {
    prjList
  });
});

/**
 * 添加项目
 */
router.post('/prj', (req, res, next) => {
  let receiveData = req.body;
  // 输入名称
  if(!!receiveData.name){
    projectModel.addProject(receiveData);
    req.session.messages = {
      type: 'success',
      msg: "项目创建成功"
    };
  } else {
    req.session.messages = {
      type: 'error',
      msg: '创建失败，需要输入名称'
    };
  }
  res.redirect('/');
});

/**
 * 编辑、预览的中间件
 */
function EditViewMiddleware(req, res, next) {
  let pid = req.params.pid;
  let projectInfo = projectModel.findProjectInfo({
    uuid: pid
  });
  let sourcePath = Tools.getProjectSourcePath(pid);
  let sourceContent = fs.readFileSync(sourcePath).toString();
  req.prj_data = {
    projectInfo,
    sourceContent,
    editorPath: global.editorPath,
    scriptTransfer: 'var projectInfo = ' + JSON.stringify(projectInfo) + ';'
  };
  //
  next();
}

/**
 * 编辑界面
 */
router.get('/edit/:pid', [EditViewMiddleware], (req, res, next) => {
  res.render('project_edit.html', {
    title: `【正在编辑】${req.prj_data.projectInfo.name || req.prj_data.projectInfo.title}`,
    ...req.prj_data
  });
});

/**
 * 预览 pre view
 */
router.get('/preview/:pid', [EditViewMiddleware], (req, res, next) => {
  res.render('template/default.html', req.prj_data);
});

// 静态资源转发
// router.use('/edit', express.static(Tools.getSourceRoot()));
router.use(global.editorPreviewPath, express.static(Tools.getSourceRoot()));

module.exports = router;